const express = require('express');
const router = express.Router();
const { Category } = require('../models');
const { Op } = require('sequelize');
const { getSignedUrl } = require('../utils/oss'); // 假设你签名逻辑放这里
// 创建分类
router.post('/create', async (req, res) => {
    const { name, parentId, image, path } = req.body;

    console.log('[category] 创建请求:', { name, parentId, image, path });

    if (!name) {
        console.warn('[category] 分类名称不能为空');
        return res.status(400).json({ code: 400, message: '分类名称不能为空' });
    }

    try {
        const category = await Category.create({
            name,
            parentId: parentId || null,
            image: image || null,
            path: path || null
        });

        console.log('[category] 创建成功:', category.toJSON());
        res.json({ code: 200, message: '分类创建成功', data: category });
    } catch (error) {
        console.error('[category] 创建失败:', error);
        res.status(500).json({ code: 500, message: '创建分类失败', error: error.message });
    }
});


// 获取所有分类
router.post('/list', async (req, res) => {
    console.log('[category] 获取分类列表');
    const { title } = req.body;

    const whereClause = {};
    if (title) {
        whereClause.name = { [Op.like]: `%${title}%` };
    }

    try {
        const categories = await Category.findAll({ order: [['id', 'ASC']], where: whereClause, });

        const categoriesWithSignedUrl = categories.map(category => {
            const data = category.toJSON();
            if (data.image) {
                try {
                    data.imageUrl = getSignedUrl(data.image); // 生成临时 URL
                    console.log("🚀 ~ data.imageUrl:", data.imageUrl)
                } catch (err) {
                    console.error('[category] 生成签名失败:', data.image, err);
                    data.imageUrl = null;
                }
            } else {
                data.imageUrl = null;
            }
            return data;
        });

        console.log('[category] 分类数量:', categoriesWithSignedUrl.length);
        res.json({ code: 200, message: '', data: { home_menu: categoriesWithSignedUrl } });
    } catch (error) {
        console.error('[category] 获取失败:', error);
        res.status(500).json({ code: 500, message: '获取分类失败', error: error.message });
    }
});


// 更新分类
router.post('/update', async (req, res) => {
    const { id, name, parentId, image, path } = req.body;



    console.log('[category] 更新请求:', { id, name, parentId });

    if (!id || !name) {
        console.warn('[category] 缺少参数:', { id, name });
        return res.status(400).json({ code: 400, message: 'ID 和分类名称不能为空' });
    }

    try {
        const category = await Category.findByPk(id);
        if (!category) {
            console.warn('[category] 分类不存在:', id);
            return res.status(404).json({ code: 404, message: '分类不存在' });
        }

        category.name = name;
        category.parentId = parentId || null;
        category.image = image || null;
        category.path = path || null;
        await category.save();

        console.log('[category] 更新成功:', category.toJSON());
        res.json({ code: 200, message: '更新成功', data: category });
    } catch (error) {
        console.error('[category] 更新失败:', error);
        res.status(500).json({ code: 500, message: '更新失败', error: error.message });
    }
});

// 删除分类
router.post('/delete', async (req, res) => {
    const { id } = req.body;

    console.log('[category] 删除请求:', { id });

    if (!id) {
        console.warn('[category] 缺少 ID');
        return res.status(400).json({ code: 400, message: 'ID 不能为空' });
    }

    try {
        const category = await Category.findByPk(id);
        if (!category) {
            console.warn('[category] 分类不存在:', id);
            return res.status(404).json({ code: 404, message: '分类不存在' });
        }

        const subCategory = await Category.findOne({ where: { parentId: id } });
        if (subCategory) {
            console.warn('[category] 存在子分类，禁止删除:', subCategory.toJSON());
            return res.status(400).json({ code: 400, message: '请先删除该分类下的子分类' });
        }

        await category.destroy();
        console.log('[category] 删除成功:', id);
        res.json({ code: 200, message: '删除成功' });
    } catch (error) {
        console.error('[category] 删除失败:', error);
        res.status(500).json({ code: 500, message: '删除失败', error: error.message });
    }
});

module.exports = router;
